﻿using Autofac;
using Autofac.Core;
using Autofac.Core.Resolving;
using AutoRegistDependency.Attributes;
using AutoRegistDependency.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AutoRegistDependency.Component
{
    /// <summary>
    /// 自定义解析参数 内部维护一个字典保存单词解析流程内的全部实例，用于解决属性/字段注入的循环依赖问题，同时可以实现dependson的优先实例化。
    /// </summary>
    internal sealed class CacheParameter : Parameter
    {
        private HashSet<object> instances =new HashSet<object> ();
        public Type CacheType { get; private set; }
        public Type CurrentType { get; set; }
        public CacheParameter(Type cacheType, Type currentType)
        {
            CacheType = cacheType;
            CurrentType= currentType;
        }
        public void AddInstance(object instance)
        {
            instances.Add(instance);
        }

        public override bool CanSupplyValue(ParameterInfo pi, IComponentContext context, out Func<object> valueProvider)
        {
            var result = false;
            valueProvider = null;
            //创建此缓存参数的组件才能使用此组件的
            if (CacheType == CurrentType)
            {
                if (pi.GetCustomAttribute<ComponentFilterAttribute>() == null)
                {
                    foreach (var instance in instances)
                    {
                        if (pi.ParameterType.IsAssignableFrom(instance.GetType()))
                        {
                            result = true;
                            valueProvider = () => instance;
                            return result;
                        }
                    }
                }
            }
            return result;
        }
    }
}
